package com.example.client_anna.util.adapter;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.example.client_anna.R;
import com.example.client_anna.module.branch_home.HomeDetailsActivity;
import com.example.client_anna.util.entity.Home_Business_Data;
import com.example.client_anna.network.okhttp3.RequestUrl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author cy
 * @email 272884043@qq.com
 * @date 2021/10/19
 */
public class HomeBusinessAdapter extends RecyclerView.Adapter<HomeBusinessAdapter.ViewHolder> {

    private Context mContext;
    private List<Home_Business_Data> mList;

    static class ViewHolder extends RecyclerView.ViewHolder{
        CardView cardView;
        ImageView homeImage;
        TextView homeTheme;
        ImageView homeMore;
        TextView homeStar;
        TextView homeSale;
        TextView homeStart;
        TextView homeDistributionText;
        TextView homeDistribution;
        TextView homeComment;
        TextView homeMinus;
        public ViewHolder(View view){
            super(view);
            cardView = (CardView) view;
            homeImage = (ImageView) view.findViewById(R.id.home_image_third);
            homeTheme = (TextView) view.findViewById(R.id.home_theme);
            homeMore = (ImageView) view.findViewById(R.id.home_more);
            homeStar = (TextView) view.findViewById(R.id.home_star);
            homeSale = (TextView) view.findViewById(R.id.home_sale);
            homeStart = (TextView) view.findViewById(R.id.home_start);
            homeDistributionText = (TextView) view.findViewById(R.id.home_distribution_text);
            homeDistribution = (TextView) view.findViewById(R.id.home_distribution);
            homeComment = (TextView) view.findViewById(R.id.home_comment);
            homeMinus = (TextView) view.findViewById(R.id.home_minus);
        }
    }

    //为适配器传入数据
    public HomeBusinessAdapter(List<Home_Business_Data> home_business_dataList){
        mList = home_business_dataList;
    }

    @NonNull
    @NotNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup viewGroup, int i) {
        if (mContext == null){
            mContext = viewGroup.getContext();
        }
        View view = LayoutInflater.from(mContext).inflate(R.layout.home_rec_third,viewGroup,false);
        ViewHolder holder = new ViewHolder(view);

        //卡片点击事件
        holder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
                Home_Business_Data data = mList.get(position);
                Intent intent = new Intent(mContext, HomeDetailsActivity.class);
                intent.putExtra(HomeDetailsActivity.HOME_BID,data.getBid());
                intent.putExtra(HomeDetailsActivity.HOME_THEME,data.getTheme());
                intent.putExtra(HomeDetailsActivity.HOME_DISTRIBUTION,data.getDistribution().toString());
                intent.putExtra(HomeDetailsActivity.HOME_STAR,data.getStar().toString());
                intent.putExtra(HomeDetailsActivity.HOME_SALE,data.getSale().toString());
                intent.putExtra(HomeDetailsActivity.HOME_START,data.getStart().toString());
                intent.putExtra(HomeDetailsActivity.HOME_MINUS,data.getFullminus());
                intent.putExtra(HomeDetailsActivity.HOME_NOTICE,data.getNotice());
                intent.putExtra(HomeDetailsActivity.HOME_IMAGE,data.getImage());
                intent.putExtra(HomeDetailsActivity.HOME_DETAIL_IMAGE,data.getDetail_image());
                mContext.startActivity(intent);
            }
        });

        //更多点击事件
        holder.homeMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
                Home_Business_Data data = mList.get(position);
                Toast.makeText(mContext,"you clicked more",Toast.LENGTH_SHORT).show();
            }
        });

        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull @NotNull HomeBusinessAdapter.ViewHolder holder, int position) {
        Home_Business_Data data = mList.get(position);
        holder.homeTheme.setText(data.getTheme());
        holder.homeStar.setText(data.getStar().toString());
        holder.homeSale.setText(data.getSale().toString());
        holder.homeStart.setText(data.getStart().toString());
        //判断是否为0，免配送费
        if(Math.abs(data.getDistribution())<0.001){
            holder.homeDistributionText.setText("");
            holder.homeDistribution.setText("免配送费");
        }else {
            //不为0，如果小数点后为0，则取整
            holder.homeDistributionText.setText("配送费 ￥");
            if(data.getDistribution().intValue()-data.getDistribution()==0){
                String distribution = String.valueOf(data.getDistribution().intValue());
                holder.homeDistribution.setText(distribution);
            }else {
                holder.homeDistribution.setText(data.getDistribution().toString());
            }
        }
        if(!("".equals(data.getComment()))) {
            holder.homeComment.setText("\""+data.getComment()+"\"");
        }else {
            holder.homeComment.setText("\"该商家还没有评论\"");
        }

        if(!("".equals(data.getFullminus()))) {
            //满减，采用键值对的形式，键对应满多少，值对应减多少
            holder.homeMinus.setText(getFullMinus(data.getFullminus()));
        }else {
            holder.homeMinus.setText("该商家还没有活动");
        }

        String url = RequestUrl.getUrl()+data.getImage();
        displayImageCenter(mContext,holder.homeImage,url);
    }
    //将json形式的字符串转成需要样式
    private String getFullMinus(String fullminus){
        HashMap<String,String> map = new HashMap<>();
        Gson gson = new Gson();
        map = gson.fromJson(fullminus,new TypeToken<HashMap<String,String>>(){}.getType());
        String toString = "\"";
        Set set = map.keySet();
        for (Iterator iterator = set.iterator();iterator.hasNext();){

            //iterator.hasNext()只是判断下一个元素的有无，并不移动指针
            //iterator.next()向下移动指针
            String key = String.valueOf(iterator.next());
            String value = String.valueOf(map.get(key));

            if (iterator.hasNext()){
                toString = toString+key+"减"+value+" | ";
            }else {
                toString = toString+key+"减"+value;
            }
        }
        return toString+"\"";
    }

    public static void displayImageCenter(Context context,final ImageView imageView,String url){
        RequestOptions options = new RequestOptions()
                //磁盘缓存
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                //内存缓存，默认false，表示不跳过内存缓存
                .skipMemoryCache(false)
                //加载错误显示的图片
                .error(R.drawable.explore_error)
                //占位图
                .placeholder(R.drawable.explore_placeholder)
                //设置图片的宽和高，获取imageView控件的宽度和高
                //注：在onCreate中是获取不到imageview的高度的，因为这个时候imageView控件自己都还没有测量
                .override(imageView.getMeasuredWidth(), imageView.getMeasuredHeight())
                //不需要动画效果，默认300
                .dontAnimate();
        //Glide缓存顺序：内存>磁盘>网络
        Glide.with(context)
                .asBitmap()
                .load(url)
                .apply(options)
                .into(imageView);
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

}
